<?php
    class Common {
    	
    	/**
    	 * 得到缓存数据
    	*
    	* @param mixed $key
    	*/
    	public static function getRedisData($key, $configName = 'default') {
    		global $redisConfig;
    		$redis = new RedisClient($redisConfig[$configName]);
    		return  $redis->get($key);
    	}
    	
    	/**
    	 * 设置缓存数据
    	 *
    	 * @param mixed $key
    	 * @param mixed $data
    	 * @param mixed $exptime
    	 */
    	public static function setRedisData($key,$data,$exptime, $configName = 'default') {
    		global $redisConfig;
    		$redis = new RedisClient($redisConfig[$configName]);
    		return $redis->set($key, $data,$exptime);
    	
    	}
    	
    	/**
    	 * 删除缓存KEY
    	 *
    	 * @param mixed $key
    	 */
    	public static function deleteRedisKey($key, $configName = 'default') {
    	
    		global $redisConfig;
    		$redis = new RedisClient($redisConfig[$configName]);
    		return $redis->delete($key);
    	}

        /**
        * 得到用户信息
        * 
        * @param bool 是否跳转,默认true
        * @param bool 是否获取等级与权限,默认false
        */
        public static function  getUserInfo($is_redirect=true,$sec_key=LOGIN_SECURE_ADMIN_KEY) {

            $sesioninfo = self::getUserSecurecrtData($sec_key);

            if(empty($sesioninfo)) {
                self::clearLoginInfo($sec_key);
                
                if($is_redirect) {
                    PageFormat::send(false, '登录失效，请重新登录', "?r=userlogin/index",false,true);
                }else {
                    return null;   
                }
            }

            return $sesioninfo;
        }


        /**
        * 获取用户登录缓存信息
        * 
        */
        private static function getUserSecurecrtData($sec_key = LOGIN_SECURE_ADMIN_KEY) {
            $userinfo = null;
            if(LOGIN_SECURE_TYPE == 1) {
                $userCookie = Cookie::get($sec_key);
                if(!empty($userCookie)) {

                    $decUserCookie = DesUtil::decrypt($userCookie);
                    if(!empty($decUserCookie)) {
                        //{"data":{"id":1,"name":"zwf"},"verify":{"i":16777343,"j":1384832000,"k":"d96463782f97f18699136909a19612a6"}}
                        //Array ( [data] => Array ( [id] => 1 [name] => zwf ) [verify] => Array ( [i] => 16777343 [j] => 1384832000 [k] => d96463782f97f18699136909a19612a6 ) ) 
                        $cookieData = @json_decode($decUserCookie,true);
                        if(!empty($cookieData)) {
                            $userjson = json_encode($cookieData["data"]);
                            $ipint = $cookieData["verify"]["i"];
                            $time = $cookieData["verify"]["j"];
                            $sign =  $cookieData["verify"]["k"];
                            $nowtime = time();

                            $nowipint = IP::convertIPToInt(IP::getIP());

                            if(($nowtime - $time) < LOGIN_SECURE_TIME ) {
                                $nowsign = md5("{$userjson}{$time}".LOGIN_SECURE_MD5KEY);

                                define("NOWIP", $nowipint);
                                define("SIGNIP", $ipint);
                                define("LASTREQUESTTIME", $time);

                                if(0 == strcasecmp($nowsign, $sign)) {
                                	self::addLoginInfo($cookieData ["data"],$sec_key);//刷新COOKIE过期时间 by soulchen
                                    return $cookieData["data"];
                                }
                            }
                        }
                    }
                }

            }else if(LOGIN_SECURE_TYPE == 2) {
                if(isset($_SESSION) && !empty($_SESSION[$sec_key])) {
                    $userinfo = json_decode($_SESSION[$sec_key],true);
                }
            }

            return $userinfo;
        }



        /**
        * 清除登录缓存信息
        * 
        */
        public static function clearLoginInfo($sec_key = LOGIN_SECURE_ADMIN_KEY) {
            if(LOGIN_SECURE_TYPE == 1){
                Cookie::set($sec_key,'',0,"/",APP_DOMAIN);
                unset($_COOKIE[$sec_key]);
            }elseif(LOGIN_SECURE_TYPE == 2){
                $_SESSION[$sec_key] = '';
            }
        }

        /**
        * 增加登录缓存信息
        * 
        * @param mixed $info
        */
        public static function addLoginInfo($info,$sec_key = LOGIN_SECURE_ADMIN_KEY) {
            if(LOGIN_SECURE_TYPE == 1){
                $userjson = json_encode($info);
                $time = time();
                $ipint = IP::convertIPToInt(IP::getIP());
                $sign = md5("{$userjson}{$time}".LOGIN_SECURE_MD5KEY);
                $cookieValue ="{\"data\":{$userjson},\"verify\":{\"i\":{$ipint},\"j\":{$time},\"k\":\"{$sign}\"}}";
                Cookie::set($sec_key,DesUtil::encrypt($cookieValue),LOGIN_SECURE_TIME,"/",APP_DOMAIN);

            }else if(LOGIN_SECURE_TYPE == 2){
                $_SESSION[$sec_key] = json_encode($info);
            }
        }

        public static function getOrderMenu() {
            $menuModule = new AdminMenuModule();
            $menu = $menuModule->getAllMenu('menuid,type,name,action_key,action,parentid',-1, null, null); //取出所有的列表

            //Array ( [0] => Array ( [menuid] => 29 [name] => 运营数据 [url] => [parentid] => 0 ) [1] => Array ( [menuid] => 30 [name] => 在线玩家 [url] => ?r=online/allonline [parentid] => 29 ) [2] => Array ( [menuid] => 31 [name] => 登录次数 [url] => ?r=loginbyhour [parentid] => 29 ) ) 

            $result = null;
            foreach($menu as $val) {
                $result[$val['parentid']][] = $val;
            }

            return $result;
        }

        /**
        * 生成下拉列表--包含所有类别
        * @param $nowValue
        * @param $keyFiled
        * @param $valueFiled
        */
        public static function makeAllMenuSelect($nowValue = '', $keyFiled = '', $valueFiled = '', $isDisabled = ''){
            if(empty($keyFiled)){
                $keyFiled = 'menuid';
            }
            if(empty($valueFiled)){
                $valueFiled = 'name';
            }
            if(empty($isDisabled)){
                $isDisabled = 'isDisabled';//是否要disabled当前下拉选项
            }
            $data = self::getAllMenuData();

            $rs = self::makeSelectOption($data, $nowValue, $keyFiled, $valueFiled, $isDisabled);
            return $rs;
        }

        /**
        * 生成下拉数据--包含所有菜单
        */
        private static function getAllMenuData(){
            $data = array();
            $parentData = array();

            //$parentMenu = $this->getAllMenu("0");//父菜单数据

            $menu = self::getOrderMenu();

            if(!empty($menu)) {
                //存在父级
                if(key_exists(0,$menu) && !empty($menu[0])) {
                    $parentMenu = $menu[0];
                }
            }

            if(!empty($parentMenu)){
                foreach ($parentMenu as $parent) {
                    $tmp = array();
                    $menuid = $parent['menuid'];
                    $tmp['menuid'] = $menuid;
                    $tmp['name'] = $parent['name'];//父菜单Name
                    //$tmp['isDisabled'] = 'true';
                    //获取子菜单数据
                    //$childrenMenu = $this->getAllMenu($menuid);

                    $childrenMenu =null;
                    if(key_exists($menuid,$menu) && !empty($menu[$menuid])) {
                        $childrenMenu = $menu[$menuid];
                    }

                    if(!empty($childrenMenu)){
                        $count = count($childrenMenu);
                        $i = 0;
                        $childrenData = array();
                        foreach ($childrenMenu as $children){
                            $i ++;
                            if($count == 1){
                                $link = ' &nbsp;&nbsp;&nbsp;<b>[</b> ';
                            }else if($i == 1 && $count > 1){
                                $link = ' &nbsp;&nbsp;&nbsp;┏ ';
                            }else if($i == $count && $count>1){
                                $link = ' &nbsp;&nbsp;&nbsp;┗ ';
                            }else{
                                $link = ' &nbsp;&nbsp;&nbsp;┣ ';
                            }
                            $childTmp = array();
                            $childTmp['menuid'] = $children['menuid'];
                            $childTmp['name'] = $link.$children['name'];//子类别Name
                            $childTmp['isshow'] = isset($children['isshow']) ? $children['isshow'] : '';//子类别是否显示
                            $childrenData[] = $childTmp;
                        }
                        $tmp['childmenu'] = $childrenData;
                    }
                    $parentData[] = $tmp;
                }
            }
            if(!empty($parentData)){
                foreach ($parentData as $k=>$p){
                    $data[] = $p;
                    if(!empty($p['childmenu']) && is_array($p['childmenu'])){
                        foreach ($p['childmenu'] as $c) {
                            $t = array();
                            $t['menuid'] = $c['menuid'];
                            $t['name'] = $c['name'];//父菜单Name
                            $t['isshow'] = isset($c['ishow']) ? $c['ishow'] : '';
                            $data[] = $t;
                        }
                        unset($data[$k]['childclass']);
                    }
                }
            }
            array_unshift($data, array('menuid'=>0,'name'=>'根菜单'));
            return $data;
        }

        /**
        * 生成下拉选择的选择内容，不包括 <select ****></select>
        * @param array $data            内容，一维数组 或  二维数组，二维数组时第一维为个数，第二维为内容
        * @param string $nowValue      当前值
        * @param string $keyFiled        二维数组时用来做 key 的字段名称
        * @param string $valueFiled    二维数组时用来做 value 的字段名称
        *
        *  
        */
        private static function  makeSelectOption($data, $nowValue = '', $keyFiled = '', $valueFiled = '', $isDisabled = '')
        {
            $result = "";
            foreach ( $data as $key => $value ) {
                if (is_array ( $value )) {
                    if (! empty ( $keyFiled ) and ! empty ( $valueFiled )) {

                        if (($value [$keyFiled] == $nowValue || $value [$valueFiled] === $nowValue) && $value [$keyFiled] != NULL) {

                            if(isset($value [$isDisabled]) && $value [$isDisabled] == "true"){
                                $result .= "<option disabled='disabled' value='" . htmlentities ( $value [$keyFiled] ) . "' selected>" . strip_tags ( $value [$valueFiled] ) . "</option>";
                            }else{
                                $result .= "<option value='" . htmlentities ( $value [$keyFiled] ) . "' selected>" . strip_tags ( $value [$valueFiled] ) . "</option>";
                            }
                        } else {
                            //echo "222|";
                            if(isset($value [$isDisabled]) && $value [$isDisabled] == "true"){
                                $result .= "<option disabled='disabled' value='" . htmlentities ( $value [$keyFiled] ) . "' >" . strip_tags ( $value[$valueFiled] ) . "</option>";
                            }else{
                                $result .= "<option value='" . htmlentities ( $value [$keyFiled] ) . "'>" . strip_tags ( $value[$valueFiled] ) . "</option>";
                            }
                        }
                    }
                } else {
                    echo 111;
                    if ($key == $nowValue || $value == $nowValue) {
                        if(isset($value [$isDisabled]) && $value [$isDisabled] == "true"){
                            $result .= "<option disabled='disabled' value='" . htmlentities ( $key ) . "' selected>" . strip_tags ( $value ) . "</option>";
                        }else{
                            $result .= "<option value='" . htmlentities ( $key ) . "'>" . strip_tags ( $value ) . "</option>";
                        }
                    } else {
                        if(isset($value [$isDisabled]) && $value [$isDisabled] == "true"){
                            $result .= "<option disabled='disabled' value='" . htmlentities ( $key ) . "' >" . strip_tags ( $value ) . "</option>";
                        }else{
                            $result .= "<option value='" . htmlentities ( $key ) . "'>" . strip_tags ( $value ) . "</option>";
                        }
                    }
                }
            }
            return $result;
        }

        /**
         * 生成导出EXCEL文件
         * @param  array  $title    第一行数据，做列标题用，array( '列字段名'=>'列标题' )
         * @param  array  $data     需要导出的数据，array( '列字段名'=>'值' )
         * @param  string $filename 文件名
         * @return
         */
        public static function saveAsExcel( $title = array(), $data = array(), $filename = '' ) {
            // echo "string";
            if ( empty( $filename ) )   $filename   =   date( 'YmdHis', time() ).'.xls'; 
            header( "Content-type:application/vnd.ms-excel" );
            header( "Content-Disposition:attachment;filename=".$filename );

            // 输出列头title
            $index  =   array();
            foreach ($title as $tk => $tv) {
                $index[]    =   $tk;
                echo mb_convert_encoding( $tv, 'GBK' )."\t";
            }
            echo "\n";

            // 输出内容data
            foreach ($data as $dk => $dv) {
                foreach ($index as $k => $v) {
                    echo mb_convert_encoding( $dv[$v], 'GBK' )."\t";
                }
                echo "\n";
            }
        }
        
        /**
         * 发送邮件
         * @param string $sendto
         */
        public static function sendEmail($sendto = '') {
            $mail = new PHPMailer();
            $mail->IsSMTP(); // send via SMTP
            $mail->Host = "smtp.bbbtgo.com"; // SMTP servers
            $mail->SMTPAuth = true; // turn on SMTP authentication
            $mail->Username = '123'; // SMTP username  注意：普通邮件认证不需要加 @域名
            $mail->Password = '123'; // SMTP password
            $mail->From = 'ghyy@bbbtgo.com'; // 发件人邮箱
        
            $mail->FromName = 'BTGO游戏运营团队'; // 发件人
        
            $mail->CharSet = "UTF-8"; // 这里指定字符集！
            $mail->Encoding = "base64";
        
            if(is_array($sendto ['sendto_email'])){
                foreach ($sendto ['sendto_email'] as $email){
                    $mail->AddAddress($email); // 收件人邮箱地址
                }
            }else{
                $mail->AddAddress($sendto['sendto_email']); // 收件人邮箱地址
            }
        
            $mail->IsHTML(true); // send as HTML
            // 邮件主题
            $mail->Subject = $sendto ['subject'];
            // 邮件内容
            $mail->Body = '<html><head><meta http-equiv="Content-Language" content="zh-cn"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  </head><body>' .
                $sendto ['body'] .
                '</body></html>';
            $mail->AltBody = "text/html";
            $send_result = $mail->Send();
            
            return $send_result;
        }

        public static function saveAsCsv($title = array(), $list = array(), $filename = ''){
            if (empty($filename)) {
                $filename = date('YmdHis', time()) . '.csv';
            } else {
                $filename .= '.csv';
            }
            $data = "";
            foreach ($title as $val) {
                $data .= "{$val},";
            }
            $data .= "\n";

            foreach ($list as $item) {
                foreach ($title as $k => $val) {
                    $data .= "{$item[$k]},";
                }
                $data .= "\n";
            }
            $encode = mb_detect_encoding($data, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"));
            $data = mb_convert_encoding($data, 'GBK', $encode);

            //输出
            header("Content-type:text/csv");
            header("Content-Disposition:attachment;filename=" . $filename);
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');
            echo $data;
            exit();
        }

        public static function toDate($time,$format='Y-m-d H:i:s'){
            if (empty($time)){
                return '';
            }
            if (!is_numeric($time)){
                $time = strtotime($time);
            }
            return date($format,$time);
        }

        public static function toTime($date){
            if (empty($date)){
                return 0;
            }
            return strtotime($date);
        }

        /**
         * 计算时间戳日期天数, 超级省钱卡不足1天按1天计算,流失天数按秒计算
         * @param $timestamp1
         * @param $timestamp2
         * @param bool $loss_day
         * @return float|int
         */
        public static function diff_days($timestamp1,$timestamp2,$loss_day=false){
            $timestamp1 = intval($timestamp1);
            $timestamp2 = intval($timestamp2);
            if ($timestamp1<=0 || $timestamp2<=0){
                return 0;
            }
            $diff = $timestamp2 - $timestamp1;
            if ($diff < 0){
                return 0;
            }
            $days = floor($diff / (60 * 60 * 24)) + ($loss_day === false ? 1 : 0);
            return $days;
        }
    }
